layui.use(['layer','form','table','element','layedit','upload'],function () {
    var layer = layui.layer
        ,form = layui.form
        ,table =layui.table
        ,element = layui.element
        ,layedit = layui.layedit
        ,transfer = layui.transfer
        ,upload = layui.upload;

    var subjectId = $("#id").val();
    var appIds = $("#appIdList").val();
    var appIdList = JSON.parse(appIds);
    var appList;

    //动态加载关联app
    $.ajax({
        type:"GET",
        url:"/admin/app/list",
        async:false,
        success:function (result) {
            appList = result;
        },
        error:function () {
            layer.msg("系统错误！");
        }
    });

    //显示搜索框
    transfer.render({
        elem: '#subjectAppList'
        ,data: appList
        ,title: ['app列表', '专题包含的app']  //自定义标题
        ,value:appIdList
        ,id:'transferData'
        ,showSearch: true
        ,parseData:function (res){
            return {
                "value":res.id,
                "title":res.title
            }
        }
    });

    var E = window.wangEditor
    var editor = new E('#addEdit1')
    // 或者 var editor = new E( document.getElementById('editor') )
    editor.customConfig.uploadImgServer = '/admin/project/uploadProjectImg2'
    editor.customConfig.uploadFileName = 'file'
    // 自定义菜单配置
    editor.customConfig.menus = [
        'head',  // 标题
        'fontSize',  // 字号
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify',  // 对齐方式
        'quote',  // 引用
        'image',  // 插入图片
        'undo',  // 撤销
        'redo'  // 重复
    ]
    editor.create();
    editor.txt.html($("#content").val());


    //普通图片上传
    var uploadInst = upload.render({
        elem: '#update_cover_btn'
        ,url: '/admin/project/uploadImg'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            console.log(res);
            var flag = res.flag;
            var message = res.message;
            if(!flag){
                layer.msg(message);
            }else{
                //上传成功,则返回url
                layer.msg("封面上传成功!");
                $("#cover_img").attr("value",res.data.url);
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });

    //表单验证
    form.verify({
        summary:function (value) {
            if(value.length == 0){
                return "简介不能为空";
            }
            if(value.length>138){
                return "长度不能超过138，当前长度为"+value.length;
            }
        },
        id:function (value) {
            if(value == ""){
                return "id不能为空";
            }
        },
        cover:function (value) {
            if(value == ""){
                return "封面不能为空";
            }
        },
        content:function () {
            var content = editor.txt.text();
            if(content == "" || content.length==0){
                return "内容不能为空";
            }
        }
    });

    //提交表单
    form.on('submit(form)',function (data) {

        layer.msg('修改中...', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 300000 });
        var summary = editor.txt.text().substring(0,108)+"...";
        var appList = transfer.getData('transferData');
        var appIdList = [];
        if(appList != null && appList.length >0){
            appList.forEach(function (obj) {
                appIdList.push(obj.value);
            });
        }

        var keyword = $("#keyword").val();
        if(keyword != null && keyword != '') {
            keyword = keyword.replaceAll("，",",");
            keyword = keyword.replaceAll("、",",");
        }

        var paramData = {
            "id":$("#id").val(),
            "title":$("#title").val(),
            "summary":summary,
            "cover":$("#cover_img").val(),
            "content":editor.txt.html(),
            "keywords":keyword,
            "appIds":appIdList,
            "isCommented":$('input[name="isCommented"]:checked ').val(),
        };

        var data2 = JSON.stringify(paramData);

        //保存项目
        $.ajax({
            url:"/admin/subject/update",
            type:"POST",
            data:data2,
            // dataType:"json",
            contentType:"application/json;charset=utf-8",
            success:function (result) {
                // console.log("data=="+form_data)
                if(result.flag){
                    layer.msg(result.message);
                    //清空内容
                    // $("#form").reset();
                    document.getElementById("form").reset();
                    layui.form.render();
                }else{
                    layer.msg(result.message);
                }
            },
            error:function () {
                layer.msg("系统错误！");
            }
        });

    });

});


